package com.augurit.wf.bi.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.augurit.common.util.PageUtils;
import com.augurit.common.util.HqlUtils;
import com.augurit.common.util.lang.StringUtils;
import com.augurit.wf.bi.convert.WfActElemPrivDefConvertor;
import com.augurit.wf.bi.convert.WfActPrinttplPrivDefConvertor;
import com.augurit.wf.bi.service.IWfActElemPrivDefService;
import com.augurit.wf.bi.service.IWfActPrinttplPrivDefService;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;
import com.augurit.wf.bi.web.form.WfActPrinttplPrivDefForm;
import com.augurit.wf.bi.web.form.WfPageElementForm;
import com.augurit.wf.bi.web.form.WfPrivControlForm;
import com.augurit.wf.common.dao.WfActElemPrivDefDao;
import com.augurit.wf.common.entity.WfActElemPrivDef;

import org.springside.modules.orm.PropertyFilter;
import org.springside.modules.orm.Page;

@Service
@Transactional
public class WfActElemPrivDefServiceImpl implements IWfActElemPrivDefService{

	@Autowired
	private WfActElemPrivDefDao wfActElemPrivDefDao;
	
	// 广州城管委行政审批修改 开始
	@Autowired
    private IWfActPrinttplPrivDefService wfActPrinttplPrivDefService;
	// 广州城管委行政审批修改 结束
	
	/**
	 * 根据主键获取Form对象
	 */
	@Transactional(readOnly = true)
	public WfActElemPrivDefForm get(Long id) {
		WfActElemPrivDef entity = wfActElemPrivDefDao.get(id);
		return WfActElemPrivDefConvertor.convertVoToForm(entity);
	}
	
	
	/**
	 * 删除Form对象列表
	 */
	public void delete(Long... ids) {
		wfActElemPrivDefDao.delete(ids);
	}

	/**
	 * 保存新增或修改的Form对象列表
	 */
	public void save(WfActElemPrivDefForm... forms) {
		if(forms != null)
			for(WfActElemPrivDefForm form : forms)
				this.save(form);
	}
	
	/**
	 * 保存新增或修改的Form对象
	 */
	public void save(WfActElemPrivDefForm form){
		
		if(form != null){
			WfActElemPrivDef entity = null;
			
			//准备VO对象
			if(form != null && form.getId() != null){
				entity = wfActElemPrivDefDao.get(form.getId());
			}else{
				entity = new WfActElemPrivDef();
			}
			
			//属性值转换
			WfActElemPrivDefConvertor.convertFormToVo(form, entity);
			
			//保存
			wfActElemPrivDefDao.save(entity);
			
			//回填ID属性值
			form.setId(entity.getId());
		}
	}

	/**
	 * 根据Form对象的查询条件作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<WfActElemPrivDefForm> search(Page<WfActElemPrivDefForm> page, WfActElemPrivDefForm form) {
		// 建立新的分页对象
		Page pg = PageUtils.newPageInstance(page);
		
		// 查询语句及参数
		StringBuffer hql = new StringBuffer("select ps, bus.templateName from WfActElemPrivDef ps,  WfBusTemplate bus where ps.templateId = bus.id");
		List values = new ArrayList();
		
		// 查询条件
		if(form != null){
			if(form.getTemplateId() != null ){
				hql.append(" and ps.templateId = ?");
				values.add(form.getTemplateId());
			}
			if(StringUtils.isNotBlank(form.getActivityName())){
				hql.append(" and ps.activityName like ?");
				values.add("%" + form.getActivityName() + "%");
			}
		}
		
		//排序
		hql.append(HqlUtils.buildOrderBy(page, "ps"));
		
		// 执行分页查询操作
		wfActElemPrivDefDao.findPage(pg, hql.toString(), values);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<WfActElemPrivDefForm> list = WfActElemPrivDefConvertor.convertObjsListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * 根据过滤条件列表作分页查询
	 */
	@Transactional(readOnly = true)
	public Page<WfActElemPrivDefForm> search(Page<WfActElemPrivDefForm> page, List<PropertyFilter> filters) {
		// 建立新的分页对象
		Page<WfActElemPrivDef> pg = PageUtils.newPageInstance(page);
		
		// 按过滤条件分页查找对象
		wfActElemPrivDefDao.findPage(pg, filters);
		
		// 转换为Form对象列表并赋值到原分页对象中
		List<WfActElemPrivDefForm> list = WfActElemPrivDefConvertor.convertVoListToFormList(pg.getResult());
		PageUtils.copy(pg, list, page);
		return page;
	}
	
	/**
	 * 获取业务流程模板中某一个流程节点的元素权限信息
	 * @param templateId
	 * @param version
	 * @param viewName
	 * @param activityName
	 * @return
	 */
	@Transactional(readOnly = true)
	public List<WfActElemPrivDefForm> getElemPrivDef(Long templateId, Integer version, String viewName, String activityName){
		if(templateId != null){
			StringBuilder hql = new StringBuilder("select priv");
			hql.append(" from WfActElemPrivDef priv");
			hql.append(" where priv.templateId = ? and priv.version = ? ");
			hql.append(" and priv.viewName = ?");
			
			List<WfActElemPrivDef> entities = null;
			
			if(viewName.equals(WfActElemPrivDefForm.DB_ZB_VIEW)){
				hql.append(" and priv.activityName = ?");
				entities = wfActElemPrivDefDao.find(hql.toString(), templateId, version, viewName, activityName);
			}
			else{
				entities = wfActElemPrivDefDao.find(hql.toString(), templateId, version, viewName);
			}
			
			return WfActElemPrivDefConvertor.convertVoListToFormList(entities);
		}
		return null;
	}
	
	public WfActElemPrivDefForm getElemPriv(String templateCode, Integer version, String viewName, String activityName, String elementCode){
		if(templateCode != null && templateCode.trim().length() > 0){
			StringBuilder hql = new StringBuilder("select priv from WfActElemPrivDef priv, WfBusTemplate temp, WfPageElement elem where priv.templateId=temp.id and priv.elementId=elem.id");
			hql.append(" and temp.templateCode = ? and elem.elementCode = ? and priv.version=?");
			hql.append(" and priv.viewName = ?");
			if(viewName.equals(WfPrivControlForm.DB_ZB_VIEW)){
				hql.append(" and priv.activityName = ?");
			}
			
			WfActElemPrivDef entity = null;
			if(viewName.equals(WfPrivControlForm.DB_ZB_VIEW)){
				entity = wfActElemPrivDefDao.findUnique(hql.toString(), templateCode, elementCode,  version, viewName, activityName);
			}
			else{
				entity = wfActElemPrivDefDao.findUnique(hql.toString() ,templateCode, elementCode,  version, viewName);
			}
			return WfActElemPrivDefConvertor.convertVoToForm(entity); 
		}
		return null;
	}
	
	/**
	 * 获取指定的业务流程下指定流程节点下的指定页面元素的权限
	 * @param templateId
	 * @param version
	 * @param viewName
	 * @param activityName
	 * @param elementId
	 * @return 如果没有指定元素在指定的业务流程下指定流程节点下的权限信息，返回null
	 */
	@Transactional(readOnly = true)
	public WfActElemPrivDefForm getElemPriv(Long templateId, Integer version, String viewName, String activityName, Long elementId){
		
		StringBuilder hql = new StringBuilder("from WfActElemPrivDef priv where priv.elementId = ? and priv.templateId = ?  and priv.version=?");
		hql.append(" and priv.viewName = ?");
		if(viewName.equals(WfPrivControlForm.DB_ZB_VIEW)){
			hql.append(" and priv.activityName = ?");
		}
		
		WfActElemPrivDef entity = null;
		if(viewName.equals(WfPrivControlForm.DB_ZB_VIEW)){
			entity = wfActElemPrivDefDao.findUnique(hql.toString(), elementId, templateId, version, viewName, activityName);
		}
		else{
			entity = wfActElemPrivDefDao.findUnique(hql.toString() ,elementId, templateId, version, viewName);
		}
		return WfActElemPrivDefConvertor.convertVoToForm(entity); 
	}
	
	/**
	 * 更新流程结点的权限信息
	 * @param list
	 * @return 修改了流程节点的权限配置信息，返回true；否则返回false
	 */
	public boolean updateActElemPriv(List<WfActElemPrivDefForm> list){
		//是否更新了权限配置
		boolean isUpdate = false;
		if(list != null && list.size() > 0){
			for(WfActElemPrivDefForm form: list){
				//WfActElemPrivDefForm privForm = this.getElemPriv(form.getTemplateId(), form.getVersion(), form.getViewName(), form.getActivityName(), form.getElementId());
				// 广州城管委行政审批修改 开始
				WfActElemPrivDefForm privForm = null;
				if(form.getElementType().equals(WfPageElementForm.PRINT_ELEM_TYPE)) {
				    privForm = wfActPrinttplPrivDefService.getElemPriv(form);
				} else {
				    privForm = this.getElemPriv(form.getTemplateId(), form.getVersion(), form.getViewName(), form.getActivityName(), form.getElementId());
				}
				// 广州城管委行政审批修改 结束
				
				//如果配置了页面元素的权限信息
				if(form.haveAlreadyConfigElemPriv()){
					
					if(privForm == null){
						privForm = new WfActElemPrivDefForm();
						
						privForm.setTemplateId(form.getTemplateId());
						privForm.setActivityName(form.getActivityName());
						privForm.setElementId(form.getElementId());
						privForm.setVersion(form.getVersion());
						privForm.setViewName(form.getViewName());
					}
					
					privForm.setHidden(form.isHidden());
					privForm.setLocked(form.isLocked());
					
					// 广州城管委行政审批修改 开始
					if (WfPageElementForm.PRINT_ELEM_TYPE.equals(form.getElementType())) {
					    WfActPrinttplPrivDefForm ptplForm = WfActPrinttplPrivDefConvertor.convertFormToForm(privForm);
					    wfActPrinttplPrivDefService.save(ptplForm);
					} else {
	                    this.save(privForm);
					}
					// 广州城管委行政审批修改 结束
					isUpdate = true;
				}
				//如果没有配置页面元素的权限信息
				else{
					//如果原来存在元素的权限配置信息去，取消其权限配置信息
					if(privForm != null){
						// 广州城管委行政审批修改 开始
						if (WfPageElementForm.PRINT_ELEM_TYPE.equals(form.getElementType())) {
					        wfActPrinttplPrivDefService.delete(privForm.getId());
					    } else {
					        this.delete(privForm.getId());
					    }
						// 广州城管委行政审批修改 结束
						isUpdate = true;
					}
				}
			}
		}
		return isUpdate;
	}
	
	public List<WfActElemPrivDefForm> getAll(){
		List<WfActElemPrivDefForm> result = null;
		
		StringBuilder hql = new StringBuilder();
		hql.append(" select def, bus.templateCode, elem.elementCode");
		hql.append(" from WfActElemPrivDef def, WfBusTemplate bus, WfPageElement elem");
		hql.append(" where bus.id = def.templateId and def.elementId = elem.id");
		hql.append(" order by def.templateId, def.activityName");
		
		List<Object[]> objs = wfActElemPrivDefDao.find(hql.toString());
		
		if(objs != null && objs.size() > 0){
			result = new ArrayList<WfActElemPrivDefForm>();
			
			for(int i = 1; i < objs.size(); i++){
				Object[] objects = objs.get(i);
				WfActElemPrivDef entity = (WfActElemPrivDef)objects[0];
				String templateCode = (String)objects[1];
				String elementCode = (String)objects[2];
				
				WfActElemPrivDefForm form = WfActElemPrivDefConvertor.convertVoToForm(entity);
				form.setTemplateCode(templateCode);
				form.setElementCode(elementCode);
				result.add(form);
			}
		}
		return result;
	}
	
	public void deleteByElemPrivInTemplate(Long templateId, Long elementId){
		String hql = "from WfActElemPrivDef def where def.templateId = ? and def.elementId = ?";
		List<WfActElemPrivDef> entities = wfActElemPrivDefDao.find(hql,templateId, elementId);
		if(entities != null && entities.size() > 0){
			wfActElemPrivDefDao.delete(entities);
		}
	}
	
	/**
	 * 把指定流程的上一版本的待在办视图流程结点权限配置导入到当前版本中，
	 * 注意：1，如果当前版本是指定流程的第一个版本，则没有权限信息可以导入。
	 *      2，导入的权限仅是当前版本和前一个版本的公共结点的权限信息
	 * @param processKey 流程
	 * @param curVersion
	 * @param preVersion
	 * @param activityNames
	 */
	public void importDbZbViewPrivFromPreVersion(Long templateId, Integer curVersion, Integer preVersion, List<String> activityNames){
		
		List<Object> values = new ArrayList<Object>();
		values.add(templateId);
		values.add(preVersion);
		
		//获取流程的当前版本的上一个版本
		StringBuilder hql = new StringBuilder(" from WfActElemPrivDef def where def.templateId = ? and def.version = ? ");
		if(activityNames != null && activityNames.size() > 0){
			hql.append(" and (");
			
			for(int i = 0; i < activityNames.size(); i++){
				hql.append(" def.activityName = ?");
				if(i != activityNames.size() - 1){
					hql.append(" or");
				}
				values.add(activityNames.get(i));
			}
			hql.append(")");
		}
		
		List<WfActElemPrivDef> entities = wfActElemPrivDefDao.find(hql.toString() , values);
		
		copyPrivToCurVersion(entities, curVersion);
	}
	
	private void copyPrivToCurVersion(List<WfActElemPrivDef> entities, Integer curversion){
		if(entities != null && entities.size() > 0){
			for(WfActElemPrivDef entity:entities){
				WfActElemPrivDef priv = new WfActElemPrivDef();
				priv.setElementId(entity.getElementId());
				priv.setActivityName(entity.getActivityName());
				priv.setIsHidden(entity.getIsHidden());
				priv.setIsLock(entity.getIsLock());
				priv.setTemplateId(entity.getTemplateId());
				priv.setVersion(curversion);
				priv.setViewName(entity.getViewName());
				
				wfActElemPrivDefDao.save(priv);
			}
		}
	}
	
	/**
	 * 导入已办、办结视图权限配置
	 * @param templateId
	 * @param curVersion
	 * @param preVersion
	 */
	public void importYbBjViewPrivFromPreVersion(Long templateId, Integer curVersion, Integer preVersion){
		//获取流程的当前版本的上一个版本
		StringBuilder hql = new StringBuilder(" from WfActElemPrivDef def where def.templateId = ? and def.version = ? and (def.viewName = ? or def.viewName = ?)");
		List<Object> values = new ArrayList<Object>();
		values.add(templateId);
		values.add(preVersion);
		values.add(WfActElemPrivDefForm.YB_VIEW);
		values.add(WfActElemPrivDefForm.BJ_VIEW);
		
		List<WfActElemPrivDef> entities = wfActElemPrivDefDao.find(hql.toString() , values);
		
		copyPrivToCurVersion(entities, curVersion);
		
	}
	
}
